package com.hue.gulimail.gulimailorder.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/25 22:31
 * @Description: 配置远程过程调用的请求拦截器
 */
@Configuration
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //RequestContextHolder:当前请求的上下文
                ServletRequestAttributes requestAttributes =
                        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes != null) {
                    //获取当前请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    //得到请求的Cookie
                    String cookie = request.getHeader("Cookie");
                    //将cookie设置到远程调用请求中
                    template.header("Cookie", cookie);
                }
            }
        };
    }
}
